'use client';

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useRouter } from 'next/navigation';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

const CommentDetail = ({ commentId }) => {
  const [comment, setComment] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const router = useRouter();

  useEffect(() => {
    // 获取评论详情
    const fetchComment = async () => {
      try {
        const response = await axios.get(`/api/comment/${commentId}`);
        if (response.data.success) {
          setComment(response.data.data);
        } else {
          throw new Error(response.data.message);
        }
      } catch (err) {
        setError(err.message || '获取评论详情失败');
        toast.error(err.message || '获取评论详情失败');
      } finally {
        setLoading(false);
      }
    };

    fetchComment();
  }, [commentId]);

  // 处理删除
  const handleDelete = async () => {
    if (window.confirm('确定要删除这条评论吗？此操作不可恢复')) {
      try {
        const response = await axios.delete(`/api/comment/${commentId}`);
        if (response.data.success) {
          toast.success('评论已成功删除');
          router.push('/admin/comments'); // 跳回列表页
        } else {
          throw new Error(response.data.message);
        }
      } catch (err) {
        toast.error(err.message || '删除失败');
      }
    }
  };

  // 处理状态修改
  const handleStatusChange = async (newStatus) => {
    try {
      const response = await axios.patch(`/api/comment/${commentId}/status`, { status: newStatus });
      if (response.data.success) {
        setComment(prev => ({ ...prev, status: newStatus }));
        toast.success('状态已更新');
      } else {
        throw new Error(response.data.message);
      }
    } catch (err) {
      toast.error(err.message || '更新状态失败');
    }
  };

  if (loading) {
    return (
      <div className={styles.loadingState}>
        <div className={styles.loadingSpinner}></div>
        <p className={styles.loadingText}>加载评论详情中...</p>
      </div>
    );
  }

  if (error || !comment) {
    return (
      <div className={styles.errorState}>
        <div className={styles.errorBox}>
          <strong>错误:</strong> {error || '评论不存在'}
        </div>
        <button
          onClick={() => router.push('/admin/comments')}
          className={styles.retryBtn}
        >
          返回列表
        </button>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      
      <div className={styles.titleSection}>
        <h1 className={styles.title}>评论详情</h1>
        <button
          onClick={() => router.back()}
          className={styles.retryBtn}
        >
          ← 返回列表
        </button>
      </div>

      <div className={styles.commentListContainer}>
        <div className={styles.detailCard}>
          <div className={styles.detailItem}>
            <span className={styles.detailLabel}>ID:</span>
            <span>{comment._id}</span>
          </div>

          <div className={styles.detailItem}>
            <span className={styles.detailLabel}>用户姓名:</span>
            <span>{comment.name}</span>
          </div>

          <div className={styles.detailItem}>
            <span className={styles.detailLabel}>用户邮箱:</span>
            <span>{comment.email}</span>
          </div>

          <div className={styles.detailItem}>
            <span className={styles.detailLabel}>评论时间:</span>
            <span>{new Date(comment.createdAt).toLocaleString()}</span>
          </div>

          <div className={styles.detailItem}>
            <span className={styles.detailLabel}>当前状态:</span>
            <span
              className={`${styles.statusBadge} ${
                comment.status === 'pending' ? styles.statusPending : 
                comment.status === 'approved' ? styles.statusApproved : 
                styles.statusRejected
              }`}
            >
              {comment.status === 'pending' ? '待审核' : 
               comment.status === 'approved' ? '已通过' : '已拒绝'}
            </span>
          </div>

          <div className={styles.detailItem}>
            <span className={styles.detailLabel}>评论内容:</span>
            <div className={styles.commentContentFull}>{comment.content}</div>
          </div>

          <div className={styles.actionBar}>
            <div className={styles.statusActions}>
              <span>修改状态:</span>
              <button
                onClick={() => handleStatusChange('pending')}
                disabled={comment.status === 'pending'}
                className={styles.actionBtn}
              >
                待审核
              </button>
              <button
                onClick={() => handleStatusChange('approved')}
                disabled={comment.status === 'approved'}
                className={styles.actionBtn + ' ' + styles.approveBtn}
              >
                批准
              </button>
              <button
                onClick={() => handleStatusChange('rejected')}
                disabled={comment.status === 'rejected'}
                className={styles.actionBtn + ' ' + styles.rejectBtn}
              >
                拒绝
              </button>
            </div>

            <button
              onClick={handleDelete}
              className={styles.actionBtn + ' ' + styles.deleteBtn}
            >
              永久删除
            </button>
          </div>
        </div>
      </div>

      <ToastContainer />
    </div>
  );
};

export default CommentDetail;